package com.eleme.food.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.eleme.food.dto.FoodAddDTO;
import com.eleme.food.dto.FoodUpdateDTO;
import com.eleme.food.entity.Food;
import com.eleme.food.mapper.FoodMapper;
import com.eleme.food.service.FoodService;
import com.eleme.food.vo.FoodVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@Service
public class FoodServiceImpl implements FoodService {
    @Autowired
    private FoodMapper foodMapper;

    @Override
    public String addFood(FoodAddDTO dto) {
        Food food = new Food();
        BeanUtils.copyProperties(dto, food);
        food.setFoodId(UUID.randomUUID().toString().replace("-", ""));
        food.setStatus(0);
        foodMapper.insert(food);
        return "添加成功";
    }

    @Override
    public String updateFood(FoodUpdateDTO dto) {
        if (!StringUtils.hasText(dto.getFoodId())) {
            throw new RuntimeException("食品ID不能为空");
        }
        Food food = foodMapper.selectById(dto.getFoodId());
        if (food == null) throw new RuntimeException("食品不存在");
        BeanUtils.copyProperties(dto, food);
        foodMapper.updateById(food);
        return "更新成功";
    }

    @Override
    public String changeStatus(String foodId, Integer status) {
        Food food = foodMapper.selectById(foodId);
        if (food == null) throw new RuntimeException("食品不存在");
        food.setStatus(status);
        foodMapper.updateById(food);
        return status == 1 ? "已下架" : "已上架";
    }

    @Override
    public List<FoodVO> listAll() {
        List<Food> list = foodMapper.selectList(null);
        List<FoodVO> res = new ArrayList<>();
        for (Food f : list) {
            FoodVO vo = new FoodVO();
            BeanUtils.copyProperties(f, vo);
            res.add(vo);
        }
        return res;
    }

    @Override
    public List<FoodVO> listByBusiness(String businessId) {
        QueryWrapper<Food> query = new QueryWrapper<>();
        query.eq("business_id", businessId);
        List<Food> list = foodMapper.selectList(query);
        List<FoodVO> res = new ArrayList<>();
        for (Food f : list) {
            FoodVO vo = new FoodVO();
            BeanUtils.copyProperties(f, vo);
            res.add(vo);
        }
        return res;
    }

    @Override
    public FoodVO getById(String foodId) {
        Food f = foodMapper.selectById(foodId);
        if (f == null) return null;
        FoodVO vo = new FoodVO();
        BeanUtils.copyProperties(f, vo);
        return vo;
    }
} 